import React, { useState, useEffect } from 'react';
import { UserSettings as UserSettingsType, ROLE_OPTIONS, PERMISSION_OPTIONS, validateUserSettings } from './SettingsTypes';

interface UserSettingsProps {
  initialSettings: UserSettingsType;
  onSettingsChange: (settings: UserSettingsType) => void;
}

const UserSettings: React.FC<UserSettingsProps> = ({ initialSettings, onSettingsChange }) => {
  const [settings, setSettings] = useState<UserSettingsType>(initialSettings);
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [isDirty, setIsDirty] = useState(false);
  const [activeTab, setActiveTab] = useState<'profile' | 'notifications' | 'permissions'>('profile');

  // 初始化设置
  useEffect(() => {
    setSettings(initialSettings);
    setIsDirty(false);
    setErrors({});
  }, [initialSettings]);

  // 处理文本输入变化
  const handleTextChange = (field: keyof UserSettingsType, value: string) => {
    setIsDirty(true);
    setSettings(prev => ({ ...prev, [field]: value }));
    
    // 清除相关错误
    if (errors[field]) {
      setErrors(prev => {
        const newErrors = { ...prev };
        delete newErrors[field];
        return newErrors;
      });
    }
  };

  // 处理通知设置变化
  const handleNotificationChange = (key: keyof UserSettingsType['notifications']) => {
    setIsDirty(true);
    setSettings(prev => ({
      ...prev,
      notifications: {
        ...prev.notifications,
        [key]: !prev.notifications[key]
      }
    }));
  };

  // 处理权限变化
  const handlePermissionChange = (permissionId: string, checked: boolean) => {
    setIsDirty(true);
    setSettings(prev => {
      if (checked) {
        // 添加权限（如果不存在）
        if (!prev.permissions.includes(permissionId)) {
          return {
            ...prev,
            permissions: [...prev.permissions, permissionId]
          };
        }
      } else {
        // 移除权限
        return {
          ...prev,
          permissions: prev.permissions.filter(p => p !== permissionId)
        };
      }
      return prev;
    });
  };

  // 处理角色变化
  const handleRoleChange = (role: string) => {
    setIsDirty(true);
    setSettings(prev => ({ ...prev, role }));
    
    // 根据角色预设权限
    let presetPermissions: string[] = [];
    
    switch (role) {
      case 'admin':
        presetPermissions = PERMISSION_OPTIONS.map(p => p.id);
        break;
      case 'teacher':
        presetPermissions = ['manageStudents', 'manageCourses', 'manageGrades', 'manageAttendance', 'viewReports'];
        break;
      case 'student':
      case 'parent':
        presetPermissions = ['viewReports'];
        break;
    }
    
    // 更新权限
    setSettings(prev => ({ ...prev, permissions: presetPermissions }));
  };

  // 处理保存
  const handleSave = () => {
    const validationErrors = validateUserSettings(settings);
    if (Object.keys(validationErrors).length === 0) {
      const updatedSettings = {
        ...settings,
        lastUpdated: new Date().toISOString()
      };
      
      onSettingsChange(updatedSettings);
      
      // 保存到本地存储
      localStorage.setItem('userSettings', JSON.stringify(updatedSettings));
      
      setIsDirty(false);
      alert('用户设置已成功保存！');
    } else {
      setErrors(validationErrors);
    }
  };

  // 处理重置
  const handleReset = () => {
    setSettings(initialSettings);
    setErrors({});
    setIsDirty(false);
  };

  // 渲染个人资料设置
  const renderProfileSettings = () => (
    <div className="profile-settings">
      <div className="setting-group">
        <label className="setting-label">
          用户名 <span className="required">*</span>
        </label>
        <input
          type="text"
          value={settings.username}
          onChange={(e) => handleTextChange('username', e.target.value)}
          className={`setting-input ${errors.username ? 'error' : ''}`}
          placeholder="请输入用户名"
        />
        {errors.username && <span className="error-message">{errors.username}</span>}
      </div>

      <div className="setting-group">
        <label className="setting-label">
          真实姓名 <span className="required">*</span>
        </label>
        <input
          type="text"
          value={settings.realName}
          onChange={(e) => handleTextChange('realName', e.target.value)}
          className={`setting-input ${errors.realName ? 'error' : ''}`}
          placeholder="请输入真实姓名"
        />
        {errors.realName && <span className="error-message">{errors.realName}</span>}
      </div>

      <div className="setting-group">
        <label className="setting-label">
          邮箱地址 <span className="required">*</span>
        </label>
        <input
          type="email"
          value={settings.email}
          onChange={(e) => handleTextChange('email', e.target.value)}
          className={`setting-input ${errors.email ? 'error' : ''}`}
          placeholder="请输入邮箱地址"
        />
        {errors.email && <span className="error-message">{errors.email}</span>}
      </div>

      <div className="setting-group">
        <label className="setting-label">用户角色</label>
        <select
          value={settings.role}
          onChange={(e) => handleRoleChange(e.target.value)}
          className="setting-select"
        >
          {ROLE_OPTIONS.map(option => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      </div>

      <div className="setting-group">
        <label className="setting-label">头像URL</label>
        <input
          type="text"
          value={settings.avatar}
          onChange={(e) => handleTextChange('avatar', e.target.value)}
          className="setting-input"
          placeholder="请输入头像URL（可选）"
        />
        {settings.avatar && (
          <div className="avatar-preview">
            <img src={settings.avatar} alt="头像预览" />
          </div>
        )}
      </div>
    </div>
  );

  // 渲染通知设置
  const renderNotificationSettings = () => (
    <div className="notification-settings">
      <h4>通知渠道</h4>
      <div className="setting-group">
        <label className="setting-checkbox-label">
          <input
            type="checkbox"
            checked={settings.notifications.email}
            onChange={() => handleNotificationChange('email')}
          />
          <span>邮件通知</span>
        </label>
        <p className="setting-description">通过邮件接收重要通知和提醒</p>
      </div>
      <div className="setting-group">
        <label className="setting-checkbox-label">
          <input
            type="checkbox"
            checked={settings.notifications.sms}
            onChange={() => handleNotificationChange('sms')}
          />
          <span>短信通知</span>
        </label>
        <p className="setting-description">通过短信接收紧急通知和重要更新</p>
      </div>
      <div className="setting-group">
        <label className="setting-checkbox-label">
          <input
            type="checkbox"
            checked={settings.notifications.push}
            onChange={() => handleNotificationChange('push')}
          />
          <span>推送通知</span>
        </label>
        <p className="setting-description">通过应用推送接收实时通知</p>
      </div>

      <h4>通知类型</h4>
      <div className="setting-group">
        <label className="setting-checkbox-label">
          <input
            type="checkbox"
            checked={settings.notifications.courseUpdates}
            onChange={() => handleNotificationChange('courseUpdates')}
          />
          <span>课程更新通知</span>
        </label>
        <p className="setting-description">接收课程内容变更、作业发布等通知</p>
      </div>
      <div className="setting-group">
        <label className="setting-checkbox-label">
          <input
            type="checkbox"
            checked={settings.notifications.gradeUpdates}
            onChange={() => handleNotificationChange('gradeUpdates')}
          />
          <span>成绩更新通知</span>
        </label>
        <p className="setting-description">接收考试成绩、作业评分等更新通知</p>
      </div>
      <div className="setting-group">
        <label className="setting-checkbox-label">
          <input
            type="checkbox"
            checked={settings.notifications.attendanceAlerts}
            onChange={() => handleNotificationChange('attendanceAlerts')}
          />
          <span>考勤异常通知</span>
        </label>
        <p className="setting-description">接收考勤异常、迟到、缺勤等提醒</p>
      </div>
      <div className="setting-group">
        <label className="setting-checkbox-label">
          <input
            type="checkbox"
            checked={settings.notifications.systemMessages}
            onChange={() => handleNotificationChange('systemMessages')}
          />
          <span>系统消息通知</span>
        </label>
        <p className="setting-description">接收系统公告、维护通知等重要信息</p>
      </div>
    </div>
  );

  // 渲染权限设置
  const renderPermissionSettings = () => (
    <div className="permission-settings">
      <p className="permission-note">
        根据用户角色自动分配基础权限，您也可以自定义权限设置
      </p>
      <div className="permission-list">
        {PERMISSION_OPTIONS.map(permission => (
          <div key={permission.id} className="setting-group">
            <label className="setting-checkbox-label">
              <input
                type="checkbox"
                checked={settings.permissions.includes(permission.id)}
                onChange={(e) => handlePermissionChange(permission.id, e.target.checked)}
                disabled={settings.role === 'admin'}
              />
              <span>{permission.label}</span>
            </label>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="user-settings">
      {/* 标签页导航 */}
      <div className="settings-tabs">
        <button 
          className={`tab-button ${activeTab === 'profile' ? 'active' : ''}`}
          onClick={() => setActiveTab('profile')}
        >
          个人资料
        </button>
        <button 
          className={`tab-button ${activeTab === 'notifications' ? 'active' : ''}`}
          onClick={() => setActiveTab('notifications')}
        >
          通知设置
        </button>
        <button 
          className={`tab-button ${activeTab === 'permissions' ? 'active' : ''}`}
          onClick={() => setActiveTab('permissions')}
        >
          权限设置
        </button>
      </div>

      {/* 标签页内容 */}
      <div className="tab-content">
        {activeTab === 'profile' && renderProfileSettings()}
        {activeTab === 'notifications' && renderNotificationSettings()}
        {activeTab === 'permissions' && renderPermissionSettings()}
      </div>

      <div className="settings-actions">
        <button
          type="button"
          className="btn-reset"
          onClick={handleReset}
          disabled={!isDirty}
        >
          重置
        </button>
        <button 
          className="btn-save" 
          onClick={handleSave}
          disabled={Object.keys(errors).length > 0 || !isDirty}
        >
          保存设置
        </button>
      </div>

      <div className="settings-note">
        <p>注意事项：</p>
        <p>• 用户名、真实姓名和邮箱地址为必填项</p>
        <p>• 角色变更会自动调整权限设置</p>
        <p>• 管理员拥有所有权限且不可修改</p>
        <p>• 用户设置将保存在本地浏览器中，更换设备或清除缓存后需要重新设置</p>
      </div>
    </div>
  );
};

export default UserSettings;